#import "PhotoSearchController.h"
#import "OFDemoAPIKey.h"
#import "WordsAppDelegate.h"
#import "ImageMO.h"
#import "WordMO.h"
#import <WebKit/DOMExtensions.h>

// we put this to make compiler happier... not absolutely necessary
@interface OFFlickrInvocation (OurOwnInvocation)
- (void)flickr_photos_search:(id)userinfo text:(NSString*)searchText selector:(SEL)aSelector;
@end

@implementation PhotoSearchController
- (void)awakeFromNib
{
	downloadLocations = [[NSMutableDictionary alloc] init];

	// we use public photos, so no shared secret here
	context = [[OFFlickrContext contextWithAPIKey:OFDemoAPIKey sharedSecret:nil] retain];
	invoc = [[OFFlickrInvocation invocationWithContext:context delegate:self] retain];
	
	// load index.html
	[[webView mainFrame] loadRequest:
		[NSURLRequest requestWithURL:
			[NSURL fileURLWithPath:
				[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"index.html"]
			]
		]
	];
	


}
- (void)dealloc
{
	[context release];
	[invoc release];
	[super dealloc];
}
- (void)handleSearch:(id)userinfo errorCode:(int)errorcode data:(id)data
{
	[progressIndicator stopAnimation:self];
	
	// error handler
	if (errorcode) {
		NSString *title = [NSString stringWithFormat:@"%@ (code %d)", 
			errorcode < 0 ? @"Connection error" : @"Flickr Error", errorcode];
		NSRunAlertPanel(title, [data description], @"Start a new search", nil, nil);
		return;
	}
		
	// get our photos
	NSArray *photos = [[data flickrDictionaryFromDocument] valueForKeyPath:@"photos.photo"];
	NSMutableString *code = [NSMutableString string];

	if ([photos isKindOfClass:[NSArray class]]) {
		unsigned i, c = [photos count];		
		for (i = 0; i < c; i++) {
			// now we combine the photos
			NSString *url=[context photoURLFromDictionary:[photos objectAtIndex:i] size:@"s" type:nil];
			[code appendString:[NSString stringWithFormat:@"<img src=\"%@\" />", url]];
		}
	}
	else {
		[code appendString:@"No photos found!"];
	}
	
	// Some AJAX stuff... :)
	DOMHTMLElement *e = (DOMHTMLElement*)[[[webView mainFrame] DOMDocument] getElementById:@"photos"];
	[e setInnerHTML:code];	
	[webView stringByEvaluatingJavaScriptFromString:@"new Effect.BlindDown('photos')"];
}

- (IBAction)startSearch:(id)sender
{
	[imageTabView selectTabViewItemWithIdentifier:@"SearchView"];
	// we convert the search string into percent-escaped string
	NSString *tags = [[[wordArrayController selectedObjects] objectAtIndex:0] valueForKey:@"word"];
	//NSString *srchstr = [[sender stringValue] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];	
	if ([tags isEqualToString:@""]) return;

	[progressIndicator startAnimation:self];
	[invoc flickr_photos_search:nil text:[tags stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] selector:@selector(handleSearch:errorCode:data:)];
}

- (IBAction)changeToBrowseView:(id)sender{
	[imageTabView selectTabViewItemWithIdentifier:@"Slideshow"];
}

#pragma mark downloading images.

//This method get's called when a url is dropped in the imageDropperView.
-(void)downloadContentsOfURL:(NSURL *)url toLocation:(NSString *)location
{
	//change the download string to be a medium sized image instead.0
	char *curl = [[[url absoluteString] stringByDeletingPathExtension] cString];
	int len = strlen(curl);
	curl[len-1] = 'm';
	url = [NSURL URLWithString:[[NSString stringWithCString:curl] stringByAppendingPathExtension:[[url absoluteString] pathExtension]]];
	
//	NSString *mediumSizedImageString
	
	// sets up the location
	NSString *homeDir = NSHomeDirectory(); //the home directory shouldn't be saved in the data store. What if it changed!
	NSString *applicationSupportFolder = [[[NSFileManager defaultManager] findSystemFolderType:kApplicationSupportFolderType 
																					 forDomain:kOnSystemDisk] stringByStandardizingPath];
	//create an image assests folder if there isn't one available already
	NSString *imageAssetsFolder = [NSString stringWithFormat:@"%@%@/Words/Images/", homeDir, applicationSupportFolder];
	[[NSFileManager defaultManager] createDirectoryAtPath:[imageAssetsFolder stringByStandardizingPath] attributes:nil];
	
	if(location == nil){ //set a default		
        location = [NSString stringWithString:imageAssetsFolder]; //actually, this always happens as implemented
	}
	
	//gets the word currently selected
	WordMO *word = [[wordArrayController selectedObjects] objectAtIndex:0];
	//create a new core data image object for the word
	NSManagedObjectContext *moc = [[NSApp delegate] managedObjectContext];
	ImageMO *newImageMO = [NSEntityDescription insertNewObjectForEntityForName:@"Image" inManagedObjectContext:moc];
	[newImageMO setValue:word forKey:@"word"];
	
	[newImageMO setValue:[url absoluteString] forKey:@"webURL"]; //where it came from
	
	//create the download request
	NSURLRequest *theRequest = [NSURLRequest requestWithURL:url
												cachePolicy:NSURLRequestUseProtocolCachePolicy
											timeoutInterval:60.0];
	
	//start the image download, naming the image with the core data name (because it's going to be uniquie :P)
	NSString *fName = [[[[newImageMO objectID] URIRepresentation] path] stringByStandardizingPath];
	NSString *actualFileName = [fName lastPathComponent]; // = xyz

	NSArray *paths = [fName pathComponents];
	NSString *entityName = [paths objectAtIndex:1];
	
	NSString *fullFolderPath = [[imageAssetsFolder stringByAppendingPathComponent:entityName] stringByStandardizingPath];
	[[NSFileManager defaultManager] createDirectoryAtPath:[fullFolderPath stringByStandardizingPath] attributes:nil];
	///user/mat/Library/Appplication Support/Words/Images/Image/ <that's the entity name
	NSString *currentImageFullPath = [applicationSupportFolder stringByAppendingPathComponent:@"Words/Images/Image"];
	currentImageFullPath = [currentImageFullPath stringByAppendingPathComponent:actualFileName];
	currentImageFullPath = [currentImageFullPath stringByAppendingPathExtension:[[url absoluteString] pathExtension]];
	[newImageMO setValue:currentImageFullPath forKey:@"creator"]; //I'm just going to use this attribute for now. TODO
	[moc processPendingChanges];
	NSError *error = nil;
    if (![moc save:&error]) {
        [[NSApplication sharedApplication] presentError:error];
    }
	NSString *completeLocation = [NSHomeDirectory() stringByAppendingPathComponent:currentImageFullPath];
	

	
	NSURLDownload  *theDownload=[[NSURLDownload alloc] initWithRequest:theRequest
															  delegate:self];
//	[downloadProgressIndicator startAnimation:nil];
	if (theDownload) {
		// set the destination file now
		[theDownload setDestination:completeLocation allowOverwrite:YES];
		NSLog(@"Download description %@", [theDownload description]);
		[downloadLocations setValue:completeLocation forKey:[theDownload description]];
	} else {
		NSLog(@"Computer Said No");
		// inform the user that the download could not be made
	}
}

- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error
{
    // release the connection
    [download release];
	
    // inform the user
    NSLog(@"Download failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}

- (void)downloadDidFinish:(NSURLDownload *)download
{	
	//do something with the data
	NSString *location = [downloadLocations objectForKey:[download description]];
	
	// release the connection
	[download release];
}

-(void)download:(NSURLDownload *)download didCreateDestination:(NSString *)path
{
    // path now contains the destination path
    // of the download, taking into account any
    // unique naming caused by -setDestination:allowOverwrite:
    NSLog(@"Final file destination: %@",path);
}

- (void)setDownloadResponse:(NSURLResponse *)aDownloadResponse 
{
    [aDownloadResponse retain];
    [downloadResponse release];
    downloadResponse = aDownloadResponse;
}

- (NSURLResponse *)downloadResponse {
	return downloadResponse;
}

- (void)download:(NSURLDownload *)download didReceiveResponse:(NSURLResponse *)response
{
    // reset the progress, this might be called multiple times
    bytesReceived=0;
	
    // retain the response to use later
    [self setDownloadResponse:response];
}

- (void)download:(NSURLDownload *)download didReceiveDataOfLength:(unsigned)length
{
    long long expectedLength=[[self downloadResponse] expectedContentLength];
	
    bytesReceived=bytesReceived+length;
	
    if (expectedLength != NSURLResponseUnknownLength) {
        // if the expected content length is 
        // available, display percent complete
        float percentComplete=(bytesReceived/(float)expectedLength)*100.0;
		//[downloadProgressIndicator setDoubleValue:percentComplete];
    } else {
        // if the expected content length is 
        // unknown just log the progress
//		[downloadProgressIndicator setIndeterminate:YES];
    }
}

- (void)importDownloadedDictionaryAtLocation:(NSString *)location{
	if(location == nil){
		NSLog(@"Error! Location to import downloaded dictionary from was nil!");
		return;
	}
	
	if([[location pathExtension] isEqualToString:@"gz"]){
		//we need to decompress the file
		NSLog(@"Decompressing dictionary at location: %@", location);
		
		NSTask *task;
		task = [[NSTask alloc] init];
		[task setLaunchPath: @"/usr/bin/gunzip"];
		
		NSArray *arguments;
		arguments = [NSArray arrayWithObjects: location, nil];
		[task setArguments: arguments];
		
	//	[downloadProgressIndicator setIndeterminate:YES];
	//	[downloadProgressIndicator startAnimation:nil];
	//	[downloaderProgressMessage setStringValue:@"Decompressing..."];
		[task launch]; //do the work
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(finishedDecompressing:) 
													 name:NSTaskDidTerminateNotification object:task];
	//	[downloaderProgressMessage setStringValue:@"Installing..."];
		return;
	}
	else{
		[self installDictAtLocation:location];
	} 
	
}

-(void)installDictAtLocation:(NSString *)location{
	id *aDictionary;
	aDictionary = [NSKeyedUnarchiver unarchiveObjectWithFile:location];
	//remove the temp file
	[[NSFileManager defaultManager] removeFileAtPath:location handler:nil];
//	[downloaderProgressMessage setStringValue:@"Finished"];
//	[downloadProgressIndicator setIndeterminate:NO];
//	[downloadProgressIndicator stopAnimation:nil];
	
}

@end
